
from . import web
from flask_login import login_required, current_user
from app.libs.enums import PendingStatus
from app.models.base import db
from app.models.drift import Drift
from app.models.gift import Gift
from flask import current_app, flash,redirect, url_for,render_template
from app.view_models.trade import MyTrades

__author__ = '七月'


@web.route('/my/gifts')
@login_required
def my_gifts():
    # uid = current_user.id
    # gifts_of_mine = Gift.get_user_gifts(uid)
    # isbn_list = [gift.isbn for gift in gifts_of_mine]
    # wish_count_list = Gift.get_wish_counts(isbn_list)
    # view_model=MyTrades(gifts_of_mine,wish_count_list)
    # return render_template("my_gifts.html",gifts=view_model.trades)
    return "你登录了，可以访问我的礼物"


@web.route('/gifts/book/<isbn>')
@login_required
def save_to_gifts(isbn):
    #事务
    #rollback   万一中途中断了，不要导致数据错误，所以要建立回滚机制，try，except一定要加
    if current_user.can_save_to_list(isbn):
        with db.auto_commit():
        # try:
            gift=Gift()
            gift.isbn=isbn
            gift.uid=current_user.id
            current_user.beans += current_app.config['BEANS_UPLOAD_ONE_BOOK']
            db.session.add(gift)
            # db.session.commit()
        # except Exception as e:
        #     db.session.rollback()
        #     raise e
    else:
        flash("这本书已添加至您的的赠送清单或已存在您的心愿清单，请不要重复添加")
    return redirect(url_for('web.book_detail',isbn=isbn))

@web.route('/gifts/<gid>/redraw')
def redraw_from_gifts(gid):
    gift = Gift.query.filter_by(id = gid,launched =False).first_or_404()
    drift = Drift.query.filter_by(gift_id = gid,pending = PendingStatus.Waiting).first()
    if drift:
        flash("礼物在交易中，请处理完鱼漂的交易，谢谢")
    else:
        with db.auto_commit():
            current_user.beans -=current_app.config["BEANS_UPLOAD_ONE_BOOK"]
            gift.delete()
    return redirect(url_for('web.my_gifts'))



